import 'package:get/get.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'package:oramemo/entity/device_mine_entity.dart';
import '../repositories/device_repository.dart';
import '../models/device.dart';

class DeviceController extends GetxController {
  final DeviceRepository _repository = DeviceRepository();
  final _isLoading = false.obs;
  final RxList<DeviceMineData> _devices = <DeviceMineData>[].obs;

  bool get isLoading => _isLoading.value;

  List<DeviceMineData> get devices => _devices;

  @override
  void onInit() {
    super.onInit();
  }

  Future<void> fetchDevices() async {
    try {
      _isLoading.value = true;
      final response = await _repository.getMyDevices();
      if (response.isSuccess && response.data?.data != null) {
        _devices.value = response.data!.data as List<DeviceMineData>;
      } else {
        Get.snackbar('Error', response.msg);
      }
    } catch (e) {
      Get.snackbar('Error', e.toString());
    } finally {
      _isLoading.value = false;
    }
  }

  Future<void> bindDevice(Map<String, String> data) async {
    try {
      _isLoading.value = true;
      final response = await _repository.bindDevice(data);
      if (response.isSuccess) {
        await fetchDevices();
        Get.back();
        Toast.show('Device bound successfully');
      } else {
        Toast.show(response.msg);
      }
    } catch (e) {
      Toast.show('绑定失败');
    } finally {
      _isLoading.value = false;
    }
  }

  Future<bool> unbindDevice(String deviceId) async {
    try {
      _isLoading.value = true;
      final response = await _repository.unbindDevice(deviceId);
      if (response.isSuccess) {
        await fetchDevices();
        return true;
      } else {
        return false;
      }
    } catch (e) {
      return false;
    } finally {
      _isLoading.value = false;
    }
  }
}
